package rw.util;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 用于读取资源文件夹中图片的工具类
 *
 * @author RWdaze
 */
public class FindPic {
    /**
     * 存储pic文件夹下面所有图片的集合
     */
    public static final HashMap<String, BufferedImage> pic = new HashMap<>();

    /**
     * 储存animation文件夹下面的所有动画。每个动画都是一个图片的集合
     */
    public static final HashMap<String, List<BufferedImage>> animation = new HashMap<>();

    /**
     * 存放图片的目标文件夹位置
     */
    private static final String picPath = "pic";

    /**
     * 存放动画的目标文件夹位置
     */
    private static final String animationPath = "animation";

    //静态代码块，初始化，并且获取资源文件夹的图片
    static {
        //获取类加载器
        ClassLoader classLoader = FindPic.class.getClassLoader();
        //获取类下路径的URL对象
        URL picPathResource = classLoader.getResource(picPath);
        URL animationPathResource = classLoader.getResource(animationPath);
        //根据两个URL对象来获得对应的路径
        String picResourcePath = null;
        String animationResourcePath = null;
        if (picPathResource != null) {
            try {
                picResourcePath = URLDecoder.decode(picPathResource.getPath(), "UTF-8");
            } catch (UnsupportedEncodingException ignored) {
            }
        }
        if (animationPathResource != null) {
            try {
                animationResourcePath = URLDecoder.decode(animationPathResource.getPath(), "UTF-8");
            } catch (UnsupportedEncodingException ignored) {
            }
        }

        //如果pic资源路径不为空
        if (picResourcePath != null) {
            foreachFilePic(picResourcePath);
        }

        //如果animation资源路径不为空
        if (animationResourcePath != null) {
            foreachFileAnimation(animationResourcePath);
        }
    }

    /**
     * 递归遍历当前文件夹下面的所有文件
     * 如果该文件为图片，则会加入到pic中
     *
     * @param path 当前文件夹
     */
    private static void foreachFilePic(String path) {
        //获取图片目标文件夹
        File picFile = new File(path);
        if (picFile.isFile()) {
            int i = path.lastIndexOf(".");
            if (i >= 0 && isPic(path.substring(i))) {
                try {
                    pic.put(picFile.getName(), ImageIO.read(picFile));
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        } else {
            File[] files = picFile.listFiles();

            if (files != null) {
                //遍历所有图片文件夹下面的图片，并加入集合
                for (File file : files) {
                    foreachFilePic(file.getPath());
                }
            }
        }
    }

    /**
     * 递归遍历当前文件夹下面的所有文件
     * 如果该文件为图片，则会加入到animation中
     *
     * @param path 当前文件夹
     */
    private static void foreachFileAnimation(String path) {
        //获取图片目标文件夹
        File picFile = new File(path);
        if (picFile.isFile()) {
            String fileName = picFile.getName();
            int i = fileName.lastIndexOf(".");
            if (i >= 0 && isPic(fileName.substring(i))) {
                String suffix = fileName.substring(i);
                int num = suffix.length();
                String fileOtherName = fileName.substring(0, fileName.length() - num);
                Pattern pattern = Pattern.compile("(.+)_\\d+");
                Matcher matcher = pattern.matcher(fileOtherName);
                if (matcher.matches()) {
                    String name = matcher.group(1);
                    if (!animation.containsKey(name)) {
                        animation.put(name, new LinkedList<>());
                    }
                    try {
                        animation.get(name).add(ImageIO.read(picFile));
                    } catch (NumberFormatException | IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        } else {
            File[] files = picFile.listFiles();

            if (files != null) {
                //遍历所有图片文件夹下面的图片，并加入集合
                for (File file : files) {
                    foreachFileAnimation(file.getPath());
                }
            }
        }
    }

    /**
     * 判断是否是图片
     *
     * @return 是否是图片
     */
    private static boolean isPic(String suffix) {
        return suffix.equalsIgnoreCase(".bmp") || suffix.equalsIgnoreCase(".jpg") || suffix.equalsIgnoreCase(".png") ||
                suffix.equalsIgnoreCase(".tif") || suffix.equalsIgnoreCase(".gif") || suffix.equalsIgnoreCase(".pcx") ||
                suffix.equalsIgnoreCase(".tga") || suffix.equalsIgnoreCase(".exif") ||
                suffix.equalsIgnoreCase(".fpx") || suffix.equalsIgnoreCase(".svg") || suffix.equalsIgnoreCase(".psd") ||
                suffix.equalsIgnoreCase(".cdr") || suffix.equalsIgnoreCase(".pcd") || suffix.equalsIgnoreCase(".dxf") ||
                suffix.equalsIgnoreCase(".ufo") || suffix.equalsIgnoreCase(".eps") || suffix.equalsIgnoreCase(".ai") ||
                suffix.equalsIgnoreCase(".raw") || suffix.equalsIgnoreCase(".WMF") || suffix.equalsIgnoreCase(".webp");
    }
}
